package com.anolesoft.amljmes.delivery.controller;

import java.io.OutputStream;
import java.net.Inet4Address;
import java.time.LocalDate;
import java.util.List;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.anolesoft.amljmes.delivery.dto.MesPtmlExportDto;
import com.anolesoft.amljmes.delivery.dto.MesPtmlIerpExportDto;
import com.anolesoft.amljmes.fortysix.controller.MesBzzPtjhInfoController;
import com.anolesoft.amljmes.fortysix.dto.PtjhExport;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.anolesoft.amljmes.delivery.dto.MesPtmlBzzDto;
import com.anolesoft.amljmes.delivery.service.MesPtmlBzzService;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.yr.demo.PageResult;
import com.anolesoft.yr.util.Constants;
import com.anolesoft.yr.util.HttpStatus;

import javax.servlet.http.HttpServletResponse;

/**
 * @author 王佳明
 * @date 2022/4/15
 */

@Slf4j
@RestController
@CrossOrigin
@RequestMapping(value = "/bzzptml")
public class MesPtmlBzzController {

    @Autowired
    private MesPtmlBzzService mesBzzPtmlService;

    @RequestMapping(value = "/querylist", method = RequestMethod.POST)
    public AjaxResult querybzzptml(@RequestBody MesPtmlBzzDto mesBzzPtmlDto) {
        String jx = mesBzzPtmlDto.getJixing();
        String th = mesBzzPtmlDto.getTuhao();
        String wlh = mesBzzPtmlDto.getWuliaohao();
        String fth = mesBzzPtmlDto.getFutuhao();
        String zy = mesBzzPtmlDto.getZhuanye();
        String czdw = mesBzzPtmlDto.getChengzhidanwei();
        String yjdw = mesBzzPtmlDto.getYijiaodanwei();
        if (jx != null) {
            mesBzzPtmlDto.setJixing(jx.toUpperCase().trim());
        }
        if (th != null) {
            mesBzzPtmlDto.setTuhao(th.toUpperCase().trim());
        }
        if (wlh != null) {
            mesBzzPtmlDto.setWuliaohao(wlh.toUpperCase().trim());
        }
        if (fth != null) {
            mesBzzPtmlDto.setFutuhao(fth.trim());
        }
        if (zy != null) {
            mesBzzPtmlDto.setZhuanye(zy.trim());
        }
        if (czdw != null) {
            mesBzzPtmlDto.setChengzhidanwei(czdw.trim());
        }
        if (yjdw != null) {
            mesBzzPtmlDto.setYijiaodanwei(yjdw.trim());
        }
        // 新加限制厂代号_sjm
        LoginUser loginUser = com.anolesoft.yr.util.SecurityUtils.getLoginUser();
        String fcode = loginUser.getFacCode();
        mesBzzPtmlDto.setChangdaihao(fcode);
        List<MesPtmlBzzDto> allList = mesBzzPtmlService.queryBzzPtml(mesBzzPtmlDto);

        Integer endIndex = mesBzzPtmlDto.getPageNumber() * mesBzzPtmlDto.getPageSize() > allList.size() ? allList.size() : mesBzzPtmlDto.getPageNumber() * mesBzzPtmlDto.getPageSize();
//        Integer aa = 0;
        List<MesPtmlBzzDto> list = allList.subList((mesBzzPtmlDto.getPageNumber() - 1) * mesBzzPtmlDto.getPageSize(), endIndex);
//        if (allList.size() < 100) {
//            aa = allList.size();
//        } else {
//            aa = 100;
//        }
//        List<MesPtmlBzzDto> list1 = allList.subList((mesBzzPtmlDto.getPageNumber() - 1) * mesBzzPtmlDto.getPageSize(), aa);

        PageResult pageResult = new PageResult(list, mesBzzPtmlDto.getPageSize(), mesBzzPtmlDto.getPageNumber(), allList.size());

        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE, pageResult);

    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @Transactional
    public AjaxResult updateBzzPtml(@RequestBody MesPtmlBzzDto mesBzzPtmlDto) {
        LoginUser loginUser = com.anolesoft.yr.util.SecurityUtils.getLoginUser();
        String Objuid = loginUser.getEmpUid();
        LocalDate date = LocalDate.now();
        mesBzzPtmlDto.setXiugaishijian(date);
        mesBzzPtmlDto.setXiugairen(Objuid);
        mesBzzPtmlDto.setChangdaihao(loginUser.getFacCode());
        int a = mesBzzPtmlService.countweihu(mesBzzPtmlDto.getWuliaohao());
        int b = 0;
        if (a == 0) {
            // 新增
            b = mesBzzPtmlService.insertweihu(mesBzzPtmlDto);
        } else {
            // 修改
            b = mesBzzPtmlService.updateBzzPtml(mesBzzPtmlDto);
        }
        System.out.println(">>>>>>update");
        return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE, b);

    }

    @PostMapping(value = "/import")
    public AjaxResult importExcelData(@RequestParam("file") MultipartFile file) {
        LocalDate date = LocalDate.now();
        LoginUser loginUser = com.anolesoft.yr.util.SecurityUtils.getLoginUser();
        String Objuid = loginUser.getEmpUid();
        MesPtmlBzzDto dto = null;
        int c = 0;
        int d = 0;
        int g = 0;
        try {
            // 通过文件输入流读取到对应的 workbook 工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            // 只解析第一张 sheet 工作表
            XSSFSheet sheet = workbook.getSheetAt(0);
            System.out.println(sheet.getPhysicalNumberOfRows() + "----------------------------------------------------");
            // 遍历第一个工作表的所有行
            for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
                XSSFRow row1 = sheet.getRow(0); // 获取工作表中的某一行，通过下标获取
                for (int j = 0; j < 19; j++) {
                    XSSFCell cell = row1.getCell(j); // 获取一行中的某个单元格，通过下标获取
                    if (cell == null) continue; // 跳过空单元格
                    cell.setCellType(CellType.STRING);//将值转字符串
                    // 判断单元格是第几个，从零开始
                    switch (j) {
                        case 0: // 机型
                            String jixing = String.valueOf(cell.getStringCellValue());
                            if (jixing.equals("机型")) {
                                c = 1;
                            } else {
                                c = 0;
                            }
                            break;
                        case 5: // 物料号
                            String wuliaohao = String.valueOf(cell.getStringCellValue());
                            if (wuliaohao.equals("物料号")) {
                                g = 0;
                            } else if (wuliaohao.equals("")) {
                                g = 0;
                            } else {
                                g = 1;
                            }
                            break;
                        case 18: // 是否做防护
                            String fh = String.valueOf(cell.getStringCellValue()).trim().replace(" ", "");
                            if (fh.equals("是否做防护")) {
                                d = 2;
                            } else {
                                d = 0;
                            }
                            break;
                    }
                }
                if (c+d+g == 3) {
                    if (i == 0) continue; // 跳过标题行
                    XSSFRow row = sheet.getRow(i); // 获取工作表中的某一行，通过下标获取
                    if (row == null) continue; // 跳过空行
                    // 构造要批量修改的MesBzzPtmlDto()对象
                    dto = new MesPtmlBzzDto();
                    // 遍历一个行中的所有列
                    for (int j = 0; j < 20; j++) {
                        XSSFCell cell = row.getCell(j); // 获取一行中的某个单元格，通过下标获取
                        if (cell == null) continue; // 跳过空单元格
//                        System.out.print(cell + "\t" + j + "\t\t\t");
                        cell.setCellType(CellType.STRING);//将值转字符串
                        // 判断单元格是第几个，从零开始
                        switch (j) {
                            case 0: // 机型
                                String jixing = String.valueOf(cell.getStringCellValue());
                                dto.setJixing(jixing.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 1: // 架次开始
                                String jiacikaishi = String.valueOf(cell.getStringCellValue());
                                dto.setJiacikaishi(jiacikaishi.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 2: // 架次结束
                                String jiacijieshu = String.valueOf(cell.getStringCellValue());
                                dto.setJiacijieshu(jiacijieshu.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 3: // 父图号
                                String futuhao = String.valueOf(cell.getStringCellValue());
                                dto.setFutuhao(futuhao.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 4: // 父零件名称
                                String fulingjianmingcheng = String.valueOf(cell.getStringCellValue());
                                dto.setFulingjianmingcheng(fulingjianmingcheng.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 5: // 物料号
                                String wuliaohao = String.valueOf(cell.getStringCellValue());
                                dto.setWuliaohao(wuliaohao.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 6: // 物料名称
                                String wuliaomingcheng = String.valueOf(cell.getStringCellValue());
                                dto.setWuliaomingcheng(wuliaomingcheng.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 7: // 类别
                                String leibie = String.valueOf(cell.getStringCellValue());
                                dto.setLeibie(leibie.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 8: // 配套数量
                                String peitaoshuliang = String.valueOf(cell.getStringCellValue());
                                if (peitaoshuliang.equals("")) {
                                    // 不进行操作
                                } else {
                                    dto.setPeitaoshuliang(Integer.parseInt(peitaoshuliang.trim().replace(" ", ""))); // 给实体类的setter属性赋值
                                }
                                break;
                            case 9: // 单位
                                String danwei = String.valueOf(cell.getStringCellValue());
                                dto.setDanwei(danwei.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 10: // 比例
                                String bili = String.valueOf(cell.getStringCellValue());
                                dto.setBili(bili.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 11: // 交付车间
                                String jiaofuchejian = String.valueOf(cell.getStringCellValue());
                                dto.setJiaofuchejian(jiaofuchejian.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 12: // 接收车间
                                String jieshouchejian = String.valueOf(cell.getStringCellValue());
                                dto.setJieshouchejian(jieshouchejian.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 13: // 交付顺序
                                String jiaofushunxu = String.valueOf(cell.getStringCellValue());
                                dto.setJiaofushunxu(jiaofushunxu.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 14: // 承制单位
                                String chengzhidanwei = String.valueOf(cell.getStringCellValue());
                                dto.setChengzhidanwei(chengzhidanwei.trim().replace(" ", "")); // 给实体类的setter属性赋值
                                break;
                            case 15: // 封存方法
                                String fengcunfangfa = String.valueOf(cell.getStringCellValue());
                                dto.setFengcunfangfa(fengcunfangfa.trim().replace(" ", ""));// 给实体类的setter属性赋值
                                break;
                            case 16: // 封存类型
                                String lx = String.valueOf(cell.getStringCellValue()).trim().replace(" ", "");
                                int a = 0;
                                if (lx.equals("外部")) {
                                    a = 1;
                                }
                                dto.setFengcunleixing(a);
                                break;
                            case 17: // 内部分工
                                String fg = String.valueOf(cell.getStringCellValue()).trim().replace(" ", "");
                                if (fg.equals("null")) {
                                    fg = null;
                                }
                                dto.setNeibufengong(fg);
                                break;
                            case 18: // 是否做防护
                                String fh = String.valueOf(cell.getStringCellValue()).trim().replace(" ", "");
                                int b = 0;
                                if (fh.equals("是")) {
                                    b = 1;
                                }
                                dto.setShifouzuofanghu(b);
                                break;

                            // 以下为 ierp集成导入导出

//						case 0: // 物料号
//							String wuliaohao=String.valueOf(cell.getStringCellValue());
//							dto.setWuliaohao(wuliaohao.trim().replace(" ", ""));
//							break;
//						case 1: // 封存方法
//							String fengcunfangfa=String.valueOf(cell.getStringCellValue());
//							dto.setFengcunfangfa(fengcunfangfa.trim().replace(" ", ""));
//							break;
//						case 2: // 封存类型
//							String lx=String.valueOf(cell.getStringCellValue()).trim().replace(" ", "");
//							int a=0;
//							if(lx.equals("外部")) {
//								a=1;
//							}
//							dto.setFengcunleixing(a);
//							break;
//                        case 3: // 内部分工
//                        	String fg=String.valueOf(cell.getStringCellValue()).trim().replace(" ", "");
//                        	if(fg.equals("null")) {
//                        		fg=null;
//                        	}
//                        	dto.setNeibufengong(fg);
//                            break;
//                        case 4: // 是否做防护
//                        	String fh=String.valueOf(cell.getStringCellValue()).trim().replace(" ", "");
//                        	int b=0;
//                        	if(fh.equals("是")) {
//                        		b=1;
//                        	}
//                        	dto.setShifouzuofanghu(b);
//                            break;
                        }

                    }
                    if (dto.getFengcunfangfa() != null && dto.getFengcunfangfa() != "") {
                        if (dto.getFengcunleixing() == 1) {
                            dto.setNeibufengong(null);
                        }
                        if (dto.getFengcunleixing() == 0) {
                            if (dto.getNeibufengong() == null || dto.getNeibufengong() == "") {
                                dto.setFengcunleixing(1);
                            }
                        }
                    } else {
                        dto.setFengcunleixing(1);
                        dto.setNeibufengong(null);
                    }
                    dto.setXiugaishijian(date);
                    dto.setXiugairen(Objuid);
                    System.out.println(dto);
                    // 用图号查询维护表  没有新增,有的修改
                    int m = mesBzzPtmlService.countweihu(dto.getWuliaohao());
                    if (m == 0) {
                        // 新增
                        dto.setChangdaihao(loginUser.getFacCode());
                        dto.setWuliaohao(dto.getWuliaohao());
                        mesBzzPtmlService.insertweihu(dto);
                    } else {
                        mesBzzPtmlService.importExcelData(dto);
                    }
                    // 新增修改主表模式,ierp集成时注掉
                    int z = mesBzzPtmlService.countPtml(dto);
                    if (z == 0) {
                        mesBzzPtmlService.insertPtml(dto);
                    } else {
                        mesBzzPtmlService.updatePtmlzhu(dto);
                    }
                } else {
                    // 不进行导入
                }
            }
            return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_SUCCESS_MESSAGE, c+d+g);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("导入失败");
            return new AjaxResult(HttpStatus.SUCCESS, Constants.QUERY_FAIL_MESSAGE, 5);
        }

    }

    // 导出
    @PostMapping(value="/export")
    public void queryMatchExport(@RequestBody MesPtmlBzzDto mesBzzPtmlDto, HttpServletResponse response){
        long start = System.currentTimeMillis();
        //OutputStream output = null;
        LoginUser loginUser = com.anolesoft.yr.util.SecurityUtils.getLoginUser();
        mesBzzPtmlDto.setChangdaihao(loginUser.getFacCode());
        log.debug("demoVO: {}", mesBzzPtmlDto);
        try {
            OutputStream output = response.getOutputStream();
            //字符集
            response.setCharacterEncoding("utf-8");
            //类型
            response.setContentType("multipart/form-data");
            //响应头
            response.setHeader("Content-Disposition", "attachment;filename="+new String(("export.xlsx").getBytes("gb2312"),"ISO8859-1"));
            //总条数
            List<MesPtmlExportDto> data = mesBzzPtmlService.queryExport(mesBzzPtmlDto);
//            List<MesPtmlIerpExportDto> data1 = mesBzzPtmlService.queryExportIerp(mesBzzPtmlDto); // ierp集成使用
//            int total = data1.size();  // ierp集成使用
            int total = data.size();
            log.debug("total:" + total);
            //单个sheet最大条数
            int size = 100000;
            //sheet数
            int sheet = total / size + 1;
            //单次查询条数
            int pageSize = 1000;
            ExcelWriter excelWriter = EasyExcel.write(output).build();
            //执行查询次数
            int count = 1;
            for (int i = 0; i < sheet ; i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i,"Sheet" + (i+1))
                        .head(MesPtmlExportDto.class)
//                        .head(MesPtmlIerpExportDto.class) // ierp集成使用
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .build();
                int rolling;
                if (i == sheet - 1) {
                    rolling = (total - i * size) / pageSize + 1;
                } else {
                    rolling = size / pageSize;
                }
                int startRow = i * size;
                for (int j = 0; j < rolling; j++) {
                    startRow = startRow + j * pageSize;
//                    int endIndex = startRow + pageSize > data1.size() ? data1.size() : startRow + pageSize; // ierp集成使用
                    int endIndex = startRow + pageSize > data.size() ? data.size() : startRow + pageSize;
//                    List<MesPtmlIerpExportDto> list = data1.subList( startRow, endIndex  ); // ierp集成使用
                    List<MesPtmlExportDto> list = data.subList( startRow, endIndex  );
                    excelWriter.write(list, writeSheet);
                    count++;
                }
            }
            log.debug("查询次数：" + (count - 1) + "次");
            //刷新流
            excelWriter.finish();
            output.flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            log.error("导出失败：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            long end = System.currentTimeMillis();
            log.debug("总用时：" + (end - start) + "毫秒");
        }
    }


}
